/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.R;
import io.renren.common.utils.RoleCode;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.dao.SysUserRoleDao;
import io.renren.modules.sys.entity.SysRoleEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.entity.SysUserRoleEntity;
import io.renren.modules.sys.form.MyRegisterForm;
import io.renren.modules.sys.form.SysLoginForm;
import io.renren.modules.sys.service.*;
import oracle.jdbc.proxy.annotation.Post;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
public class SysLoginController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private SysCaptchaService sysCaptchaService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	public Map<String, Object> login(@RequestBody SysLoginForm form)throws IOException{
		Map<String, Object> resultMapInfo = loginProcess(form);
		return resultMapInfo;
	}

	private Map<String,Object> loginProcess(SysLoginForm form) {
		//第一步，判断验证码
		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if (!captcha) {
			return R.error("验证码不正确");
		}

		String clientOrServer = form.getClientOrServer();
		//第二步，验证是客户端登录还是服务端登录
		if ("1".equals(clientOrServer)) {
			//第三步，验证客户端的登录用户是个人还是企业
			if ("2".equals(form.getCompanyOrPerson())) {
				QueryWrapper<SysUserEntity> sysUserEntityWrapper = new QueryWrapper<>();
				sysUserEntityWrapper.eq("username", form.getUsername());
				SysUserEntity sysUserEntity = sysUserDao.selectOne(sysUserEntityWrapper);
				//个人的用户的账号是否存在
				if (sysUserEntity == null) {
					return R.error("此个人用户不存在呢！！！");
				}
				QueryWrapper<SysUserRoleEntity> sysUserRoleEntityWrapper = new QueryWrapper<>();
				sysUserRoleEntityWrapper.eq("user_id", sysUserEntity.getUserId());
				SysUserRoleEntity userRoleEntity = sysUserRoleDao.selectOne(sysUserRoleEntityWrapper);
				//判断用户是否有角色信息
				if (userRoleEntity == null) {
					return R.error("此用户不属于任何角色！！！");
				}
				//判断这个用户是否是属于个人用户
				if (!RoleCode.PERSONAL_ROLE.equals(userRoleEntity.getRoleId())) {
					return R.error("请使用求职者用户登录呢！！！");
				}
				//接下来是密码验证
				if (!sysUserEntity.getPassword().equals(new Sha256Hash(form.getPassword(), sysUserEntity.getSalt()).toHex())) {
					return R.error("个人用户账号密码不正确呢");
				}

				//账号是否正常
				if (sysUserEntity.getStatus() == 0) {
					return R.error("账号已被锁定,请联系管理员");
				}

				//生成token，并保存到数据库,每一次登录会生成不同的Token
				R r = sysUserTokenService.createToken(sysUserEntity.getUserId(),form.getClientOrServer());
				return r;
			}

			if ("3".equals(form.getCompanyOrPerson())) {
				QueryWrapper<SysUserEntity> sysUserEntityWrapper = new QueryWrapper<>();
				sysUserEntityWrapper.eq("username", form.getUsername());
				SysUserEntity sysUserEntity = sysUserDao.selectOne(sysUserEntityWrapper);
				//企业的用户的账号是否存在
				if (sysUserEntity == null) {
					return R.error("此企业用户不存在呢！！！");
				}
				QueryWrapper<SysUserRoleEntity> sysUserRoleEntityWrapper = new QueryWrapper<>();
				sysUserRoleEntityWrapper.eq("user_id", sysUserEntity.getUserId());
				SysUserRoleEntity userRoleEntity = sysUserRoleDao.selectOne(sysUserRoleEntityWrapper);
				//判断用户是否有角色信息
				if (userRoleEntity == null) {
					return R.error("此用户不属于任何角色！！！");
				}
				//判断这个用户是否是属于企业用户
				if (!RoleCode.COMPANY_ROLE.equals(userRoleEntity.getRoleId())) {
					return R.error("请使用企业用户登录呢！！！");
				}
				//接下来是密码验证
				if (!sysUserEntity.getPassword().equals(new Sha256Hash(form.getPassword(), sysUserEntity.getSalt()).toHex())) {
					return R.error("企业用户账号密码不正确呢");
				}
				//账号是否正常
				if (sysUserEntity.getStatus() == 0) {
					return R.error("账号已被锁定,请联系管理员");
				}
				//生成token，并保存到数据库,每一次登录会生成不同的Token
				R r = sysUserTokenService.createToken(sysUserEntity.getUserId(),form.getClientOrServer());
				return r;
			}
		} else {
			//服务端登录
			QueryWrapper<SysUserEntity> sysUserEntityWrapper = new QueryWrapper<>();
			sysUserEntityWrapper.eq("username", form.getUsername());
			SysUserEntity sysUserEntity = sysUserDao.selectOne(sysUserEntityWrapper);
			//管理员或者猎头的用户的账号是否存在
			if (sysUserEntity == null) {
				return R.error("此用户不存在呢！！！");
			}


			QueryWrapper<SysUserRoleEntity> sysUserRoleEntityWrapper = new QueryWrapper<>();
			sysUserRoleEntityWrapper.eq("user_id", sysUserEntity.getUserId());
			SysUserRoleEntity userRoleEntity = sysUserRoleDao.selectOne(sysUserRoleEntityWrapper);
			//判断用户是否有角色信息
			if (userRoleEntity == null) {
				return R.error("此用户不属于任何角色！！！");
			}
			//判断这个用户是否是属于猎头或者管理员用户
			if (!(RoleCode.SUPER_ADMIN.equals(userRoleEntity.getRoleId())
					||
					RoleCode.SUB_ADMIN.equals(userRoleEntity.getRoleId()))) {
				return R.error("请使用管理员用户或者子管理员用户登录呢！！！");
			}
			//接下来是密码验证
			if (!sysUserEntity.getPassword().equals(new Sha256Hash(form.getPassword(), sysUserEntity.getSalt()).toHex())) {
				return R.error("管理员用户密码不正确呢");
			}
			//账号是否正常
			if (sysUserEntity.getStatus() == 0) {
				return R.error("账号已被锁定,请联超级系管理员");
			}
			//生成token，并保存到数据库,每一次登录会生成不同的Token
			R r = sysUserTokenService.createToken(sysUserEntity.getUserId(),form.getClientOrServer());
			return r;
		}
		return R.ok();
	}

	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public R logout() {
		sysUserTokenService.logout(getUserId());
		return R.ok();
	}










	
}
